<template>
  <el-dialog
    :title="type"
    :visible.sync="dialogVisible"
    width="30%"
    :before-close="setdialogVisible"
  >
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="ruleForm.name" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="ruleForm.code" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="ruleForm.manager" placeholder="请选择" @focus="validateManager">
          <el-option v-for="item in optionList" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="ruleForm.introduce" type="textarea" placeholder="1-300个字符" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setdialogVisible">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartment, getDepartment, setDepartment } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  name: 'Additem',
  props: ['dialogVisible', 'type', 'id'],
  data() {
    const validateName = async(rule, value, callback) => {
      await this.getValidator('name', value) ? callback(new Error('该部门名称已存在')) : callback()
    }
    const validateCode = async(rule, value, callback) => {
      await this.getValidator('code', value) ? callback(new Error('该部门编码已存在')) : callback()
    }
    return {
      ruleForm: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: this.id
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请填写活动形式', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }
        ]
      },
      optionList: []
    }
  },
  async created() {
    if (this.type === '编辑部门') {
      const res = await getDepartment(this.id)
      this.ruleForm = res
    }
  },
  methods: {
    // 取消
    setdialogVisible() {
      this.$emit('update:dialog-visible', false)
    },
    // 确定
    submitForm() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.type === '编辑部门') {
            this.ruleForm.createTime = Date.now()
            try {
              await setDepartment(this.id, this.ruleForm)
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              this.$emit('update')
            } catch (error) {
              this.$message.error('修改失败')
            }
          } else {
            try {
              await addDepartment(this.ruleForm)
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
              this.$emit('update')
            } catch (error) {
              this.$message.error('添加失败')
            }
          }
          this.$emit('update:dialog-visible', false)
        }
      })
    },
    // 获取下拉框数据
    async validateManager() {
      const res = await getEmployeeSimple()
      this.optionList = res
    },
    // 定义一个校验函数
    async getValidator(attr, value) {
      const res = await getDepartments()
      let isDone = null
      if (this.type === '编辑部门') {
        isDone = res.depts.filter(item => (item.pid === this.ruleForm.pid) && (item.id !== this.id)).some(item => item[attr] === value)
      } else {
        isDone = res.depts.filter(item => item.pid === this.id).some(item => item[attr] === value)
      }
      return isDone
    }
  }
}
</script>

<style>

</style>
